<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:20px;float:right">
      <el-button type="primary" @click="handleCreate">新增广告</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='ID' min-width="80" prop="id"></el-table-column>
      <el-table-column align="center" label='名称' min-width="110" prop="adName"></el-table-column>
      <el-table-column class-name="status-col" label="图片" min-width="240" align="center">
        <template slot-scope="scope">
          <div class="row-div-ctx" v-if="scope.row.adIconUrl != ''">
            <img :src="scope.row.adIconUrl" class="row-div-ctx-img"/>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column min-width="240" label="跳转" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.hrefUrl.length == 0 ? '--' : scope.row.hrefUrl }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="sort" label="权重" min-width="120" sortable :sortBy="['sort','startTime']"></el-table-column>
      <el-table-column align="center" prop="inTime" label="有效时间" min-width="220" sortable >
        <template slot-scope="scope">{{scope.row.startTime|dateformat('YYYY-MM-DD HH:mm')}} 至 {{scope.row.endTime|dateformat('YYYY-MM-DD HH:mm')}}</template>
      </el-table-column >
      <el-table-column label="状态" min-width="110" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.displayDesc}}</span>
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="240">
        <template slot-scope="scope">
          <el-button size="small" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="small" type="primary" v-if="scope.row.status == 0" @click="handleOprate(scope.row,1)">下架</el-button>
          <el-button size="small" type="primary" v-else @click="handleOprate(scope.row,0)">上架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[5,10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="dialogStatus=='create' ? '新增广告' : '编辑广告'" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="广告名称" label-width="110px" prop="adName">
          <el-input v-model="form.adName" auto-complete="off" maxlength="10"
          placeholder="请输入广告名称（不超过10个字）"></el-input>
        </el-form-item>
        <el-form-item label-width="110px" label="跳转类型" class="postInfo-container-item" prop="hrefType">
          <el-col :span="12">
            <el-select v-model="form.hrefType" placeholder="请选择跳转类型">
              <el-option
                v-for="item in brandListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-tooltip  class="item" effect="dark" :content="holderVal.placeholder" placement="top">
          <el-form-item label-width="110px" :label="holderVal.name" class="postInfo-container-item" prop="hrefUrl" v-if="form.hrefType == 2">
            <el-col :span="24">
              <el-input  :placeholder="holderVal.placeholder" v-model="form.hrefUrl" @input.native='deleteSpace'>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item label-width="110px" :label="holderVal.name" class="postInfo-container-item" prop="bindId" v-else>
            <el-col :span="24">
              <el-input  :placeholder="holderVal.placeholder" v-model="form.bindId">
              </el-input>
            </el-col>
          </el-form-item>
        </el-tooltip>
        <el-form-item label="权重" label-width="110px" prop="sort">
          <el-input-number  v-model="form.sort" :step="1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label-width="110px" label="活动时间：" class="postInfo-container-item" prop="time">  
            <el-col :span="12">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                :picker-options="pickerOptions2"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
              </el-date-picker>
            </el-col>
        </el-form-item>
        <el-form-item label-width="110px" label="广告图" class="postInfo-container-item" prop="adIconUrl">
            <el-input v-model="form.adIconUrl" type='text' style='display:none'></el-input>
            <el-upload
            ref="upload"
            :headers="headers"
            action="/tools/oss/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            list-type="picture"
            :accept="'.png,.jpg,.jpeg,.gif'"
            :limit="2">
            <el-button size="small" type="primary" adIconUrl="el-adIconUrl-upload2">点击此处上传图片</el-button>
            <div slot="tip" class="el-upload__tip">注：建议尺寸：1242X700px</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, add, update, getId, toggleId } from '@/api/advertising'
import { getToken } from '@/utils/auth'
import { validateURL } from '@/utils/validate'

export default {
  data() {
    return {
      time:'',
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      holderVal:{
        placeholder:'请输入商品ID',
        name:'商品ID'
      },
      holderMap:[{
        placeholder:'请输入商品ID',
        name:'商品ID'
      }, {
        placeholder:'请输入资讯ID',
        name:'资讯ID'
      }, {
        placeholder:'请输入跳转链接',
        name:'跳转链接'
      }],
      brandListOptions: [{
        id:0,
        name:'课程'
      }, {
        id:1,
        name:'资讯'
      }, {
        id:2,
        name:'网页'
      }],
      listQuery: {
        'apiVersion': '',
        'keyword': '',
        'orderBy': '',
        'pageNo': 1,
        'pageSize': 5,
        'platform': 'ALL',
        'searchName': '',
        'sortField': ''
      },
      fileList:[],
      headers:{},
      dialogStatus:'create',
      form:{
        id:0,
        adIconUrl:'',
        adName:'',
        sort:1,
        bindId:0,
        startTime:'',
        endTime:'',
        hrefUrl:'',
        hrefType:0
      },
      dialogFormVisible:false,
      list: null,
      listLoading: true,
      total:0,
      rules: {
        adName: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序权重', trigger: 'blur' }],
        hrefType: [{ required: true, message: '跳转类型必选', trigger: 'change' }],
        hrefUrl: [
          { required: true, message: '内容必填', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.headers = { accessToken:getToken() }
    this.getList()
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0':'投放中',
        '1':'已下架'
      }
      return statusMap[status]
    }
  },
  methods: {
    deleteSpace(e){
      this.$nextTick(() => {
        this.form.hrefUrl = e.target.value.replace(/\s/g, '')
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleUploadSuccess(rst, file, fileList){
      const { code, data:{ picUrlList } } = rst
      const { form } = this
      if(code == 0){
        this.form.adIconUrl = picUrlList[0]
        this.fileList = [{ name:file.url, url:file.url }]
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      if(fileList.length == 0){
        this.form.adIconUrl = ''
        this.$refs.upload.clearFiles()
      }
    },
    handleChange(row){
      row['selected'] = !row['selected']
    },
    handleUpdate(row){
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      getId({ id:row.id }).then(response => {
        const { code, message, data } = response
        const { adIconUrl } = data
        if(code == 0){
          const { from } = this
          this.time = [new Date(data.startTime), new Date(data.endTime)]
          if(adIconUrl.length != 0){
            this.fileList = [{ name:adIconUrl, url:adIconUrl }]
          }else{
            this.fileList = []
          }
          this.form = data
        }else{
          this.$message(message)
        }
      })
    },
    handleCreate() {
      const end = new Date()
      const start = new Date()
      end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
      this.time = [start, end]
      this.form = {
        id:0,
        adIconUrl:'',
        adName:'',
        sort:1,
        bindId:0,
        startTime:'',
        endTime:'',
        hrefUrl:'',
        hrefType:2
      }
      this.fileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    updateForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = this.form
          let { form:{ hrefType, hrefUrl, bindId }, time } = this
          if(!time){
            this.$notify({
              message: '活动时间必填',
              type: 'error',
              duration: 1000
            })
            this.loading = false
            return
          }
          if(hrefType == 0 || hrefType == 1){
            bindId = parseInt(bindId)
            const skiptext = this.holderMap[hrefType].name.replace('：', '')
            if(!/^\d+$/.test(bindId)){
              this.$notify({
                message: skiptext + '必须是数字',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
            params['bindId'] = bindId
          }else if(hrefType == 2){
            if(!validateURL(hrefUrl.trim())){
              this.$notify({
                message: '请输入正确的url',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
          }
          params['startTime'] = time[0]
          params['endTime'] = time[1]
          update(params).then(response => {
            const { code, message } = response
            if(code == 0){
              this.getList()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = this.form
          let { form:{ hrefType, hrefUrl, bindId }, time } = this
          if(!time){
            this.$notify({
              message: '活动时间必填',
              type: 'error',
              duration: 1000
            })
            this.loading = false
            return
          }
          if(hrefType == 0 || hrefType == 1){
            bindId = parseInt(bindId)
            const skiptext = this.holderMap[hrefType].name.replace('：', '')
            if(!/^\d+$/.test(bindId)){
              this.$notify({
                message: skiptext + '必须是数字',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
            params['bindId'] = bindId
          }else if(hrefType == 2){
            if(!validateURL(hrefUrl.trim())){
              this.$notify({
                message: '请输入正确的url',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
          }
          params['startTime'] = time[0]
          params['endTime'] = time[1]
          // return;
          add(params).then(response => {
            const { code, message } = response
            if(code == 0){
              this.getList()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    handleOprate(row, type){
      this.$confirm(`你确定要将此广告“${row.adName}”${type == 1 ? '下架' : '上架'}？`)
        .then(() => {
          toggleId({ ids:[row.id], operateType:type }).then(res => {
            const { code } = res
            if(code == 0){
              this.$notify({
                message: `${type == 1 ? '下架' : '上架'}成功`,
                type: 'success',
                duration: 2000
              })
              row['status'] = type
              if(type == 1){
                row['displayDesc'] = '未投放'
              }
            }
          })
        })
        .catch(() => {})
    },
    getList() {
      const { pageNo, pageSize } = this.listQuery
      this.listLoading = true
      getList({ pageNo, pageSize }).then(response => {
        this.list = response.data['list']
        this.total = response.data['total']
        this.listLoading = false
      })
    }
  },
  watch:{
    'form.hrefType'(val){
      if(!val){ val = 0 }
      this.holderVal = this.holderMap[val]
      if(val == 2 && this.form.hrefUrl.includes('shengxue://')){
        this.form.hrefUrl = ''
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.row-div-ctx{
  width:160px;
  height:80px;
  overflow:hidden;
  margin:0 auto;
}
.row-div-ctx-img{
  width:160px;
}
.pagination-container{
  margin-top:30px;
}
.checkbox-item{
    margin-right:30px;
    margin-left:0;
  }
</style>
